// detect_logger
package logging

import (
	"github.com/natefinch/lumberjack"
	"github.com/spf13/viper"
	"os"
	"strings"

	"log"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

const (
	defaultLogNameK  = "logging.file"
	defaultLogLevelK = "logging.level"
)

var InfoLevel zapcore.LevelEnabler = zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
	return lvl >= zapcore.InfoLevel
})

var DebugLevel zapcore.LevelEnabler = zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
	return lvl >= zapcore.DebugLevel
})

func NewLogger(vp *viper.Viper) (ret *zap.SugaredLogger) {
	log.Println("configuring log")
	var level zapcore.LevelEnabler
	if strings.ToLower(vp.GetString(defaultLogLevelK)) == "debug" {
		level = DebugLevel
	} else {
		level = InfoLevel
	}
	if vp.GetString(defaultLogNameK) != "" {
		fileName := vp.GetString(defaultLogNameK)
		log.Println("log to file", fileName)
		core := zapcore.NewCore(getDevelopmentConsoleEncoder(), getRollingFileWs(fileName, 200), level)
		logger := zap.New(core, zap.AddCaller())
		ret = logger.Sugar()
	} else {
		log.Println("log to console")
		core := zapcore.NewCore(getDevelopmentConsoleEncoder(), getConsoleWs(), level)
		logger := zap.New(core, zap.AddCaller())
		ret = logger.Sugar()
	}
	return ret
}

func CloseLogger(logger *zap.SugaredLogger) {
	log.Println("closing log")
	err := logger.Sync()
	log.Println("log closed", err)
}

// 返回一个滚动的日志
func getRollingFileWs(logfile string, maxsize int) zapcore.WriteSyncer {
	rf := &lumberjack.Logger{
		Filename:   logfile,
		MaxSize:    maxsize,
		MaxBackups: 100,
		MaxAge:     30, //天
		Compress:   false,
	}
	return zapcore.AddSync(rf)
}

// 控制台写
func getConsoleWs() zapcore.WriteSyncer {
	return zapcore.AddSync(os.Stdout)
}

// 返回一个开发的encoder
func getDevelopmentConsoleEncoder() zapcore.Encoder {
	conf := zap.NewDevelopmentEncoderConfig()
	conf.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.000")
	return zapcore.NewConsoleEncoder(conf)
}
